
/*
1.	Obtener los maximos IDs + su nombre. Los ids de las tablas estan con diferentes nombres
Utilizar sys.tables + columnS object_id
Tomar en cuenta q customerID es varchar, no int

*/


DECLARE @Tarea1 TABLE (
						   ID INT IDENTITY (1,1),
						   TABLA VARCHAR(50),
						   COLID NVARCHAR(100),
						   MaxId NVARCHAR(MAX)
					   )

DECLARE @Query NVARCHAR(MAX)
		,@Tabla NVARCHAR(100)
		,@Col NVARCHAR(100)
		, @MaxId NVARCHAR(MAX)

DECLARE qTablas CURSOR FOR
	SELECT T.name, C.name
		FROM sys.tables T
			JOIN sys.columns C ON T.object_id = C.object_id
		WHERE C.column_id = 1

OPEN qTablas
FETCH NEXT FROM qTablas INTO @Tabla, @Col
WHILE @@FETCH_STATUS = 0
BEGIN 
	

	SET @Query = N'SELECT @IdM= Max' + Quotename(@Col, '(') + ' FROM ' + Quotename(@Tabla)
	EXEC sp_executesql @Query,N'@IdM NVARCHAR(50) OUTPUT', @IdM = @MaxId OUTPUT

	INSERT INTO @Tarea1(TABLA, COLID, MaxId) VALUES (@Tabla, @Col, @MaxId)

	FETCH NEXT FROM qTablas INTO  @Tabla, @Col 

END

CLOSE qTablas 
DEALLOCATE qTablas

SELECT * FROM @Tarea1


